const API_KEY = 'T17Er9gy8iym7snOSUWVxFpO';
const CLIENT_ID = '761356501830-fekd5q8i13c6h5rtft203cd9jp2utcqo.apps.googleusercontent.com';
const SCOPE = 'profile'; //https://www.googleapis.com/auth/userinfo.profile
let GoogleAuth;

function setSigninStatus(callback) {
  const user = GoogleAuth.currentUser.get();
  const isAuthorized = user.hasGrantedScopes(SCOPE);
  if (isAuthorized) {
    console.log('You are currently signed in and have granted.');
    callback(user);
  } else {
    console.log('You have not authorized this app.');
    callback(null);
  }
}

export const initClient = (callback) => {
  return new Promise((resolve) => {
    window.gapi.load('client:auth2', () => {
      window.gapi.client
        .init({
          apiKey: API_KEY,
          clientId: CLIENT_ID,
          scope: SCOPE,
          cookiepolicy: 'single_host_origin',
        })
        .then(() => {
          GoogleAuth = window.gapi.auth2.getAuthInstance();
          GoogleAuth.isSignedIn.listen(() => {
            setSigninStatus(callback);
          });
          setSigninStatus(callback);
          resolve(GoogleAuth);
        });
    });
  });
};

export const doLogin = (callback) => {
  // if (GoogleAuth) {
  //   GoogleAuth.signIn();
  // } else {
    initClient(callback).then((instance) => {
      instance.signIn();
    });
  // }
};
